package service

import (
	"cangqiong-takeout/src/common"
	"cangqiong-takeout/src/model"
	"cangqiong-takeout/src/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

func GetDishMsg(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("pageSize"))
	categoryId := c.Query("categoryId") //分类id
	name := c.Query("name")
	status, _ := strconv.Atoi(c.Query("status")) //状态
	fmt.Printf("前端数据value=%v", size)
	offset := (page - 1) * size
	if categoryId != "" || name != "" || status != 0 {
		dish, i, err := getDish(size, offset, categoryId, name, status)
		if err != nil {
			utils.ResponseBad(c, common.FindError, nil)
			return
		}
		utils.ResponseSuccess(c, common.FindSuccess, gin.H{
			"total":   i,
			"records": dish,
		})
		return
	}
	var (
		dish []*model.Dish[float64]
		cnt  int64
	)
	if err := utils.MysqlDB.Table("dish").Count(&cnt).Limit(size).Offset(offset).Find(&dish).Error; err != nil {
		utils.ResponseBad(c, common.FindError, nil)
		return
	}
	for i := 0; i < len(dish); i++ {
		dish[i].SetStringToCreateTime()
		dish[i].SetStringToUpdateTime()
		dish[i].SetImage(dish[i].Image)
		utils.MysqlDB.Table("category").Raw("select name from category where `id`=?", dish[i].CategoryID).Scan(&dish[i].CategoryName)
	}
	utils.ResponseSuccess(c, common.FindSuccess, gin.H{
		"total":   cnt,
		"records": dish,
	})
}

func getDish(pageSize, offset int, categoryId, name string, s int) ([]*model.Dish[float64], int64, error) {
	var (
		dish []*model.Dish[float64]
		cnt  int64
	)
	if err := utils.MysqlDB.Table("dish").Where("category_id like ? AND name like ? AND status like ?", "%"+categoryId+"%", "%"+name+"%", "%"+strconv.Itoa(s)+"%").Count(&cnt).Limit(pageSize).Offset(offset).Find(&dish).Error; err != nil {
		return nil, 0, err
	}
	for i := 0; i < len(dish); i++ {
		dish[i].SetStringToCreateTime()
		dish[i].SetStringToUpdateTime()
		dish[i].SetImage(dish[i].Image)
		utils.MysqlDB.Table("category").Raw("select name from category where `id`=?", dish[i].CategoryID).Scan(&dish[i].CategoryName)
	}
	return dish, cnt, nil
}

func GetDishList(c *gin.Context) {

}
